/**
 * @author Created by qiush on 2017-07-11.
 */

import {IView} from '../types/IView';
import isParentView, {IParentView} from '../types/IParentView';
import {AppState} from '../store/index';

export interface IChildSelectionOwnProps {
  designId: string;
  view: IParentView;
}

export interface IChildSelectionMergedProps {
  current: number;
}

export type IChildSelectionProps = IChildSelectionOwnProps & IChildSelectionMergedProps;

export function mapStateToProps(
  state: AppState,
  ownProps: IChildSelectionOwnProps
): IChildSelectionMergedProps {
  const designId: string = ownProps.designId;

  const selectedView: IView = state.selectedViewState[designId];
  // 看当前选中的组件是这个子组件里面的第几个元素
  const current: number = _findCurrentView(ownProps.view, selectedView);
  return {
    current
  };
}

function _findCurrentView(view: IParentView, selectedView: IView) {
  if (!selectedView) {
    return -1;
  }

  return view.children.findIndex((childView: IView) => {
    if (childView.id === selectedView.id) {
      return true;
    }
    if (!isParentView(childView)) {
      return false;
    }
    return _findCurrentView(childView, selectedView) >= 0;
  });
}
